package com.ruoyi.web.controller.net;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.net.domain.*;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.IBusiElementStatusService;
import com.ruoyi.net.service.IBusiNeighbLabelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * 业务管理-邻接标签Controller
 * 
 * @author tony
 * @date 2024-12-11
 */
@Api(tags = "业务管理-邻接标签")
@RestController
@RequestMapping("/busi/neighb/label")
public class BusiNeighbLabelController extends BaseController
{
    @Autowired
    private IBusiNeighbLabelService busiNeighbLabelService;

    @Autowired
    private DeviceManager deviceManager;

    @Autowired
    private IBusiElementStatusService busiElementStatusService;
    /**
     * 查询业务管理-邻接标签列表
     */
    @ApiOperation(value = "查询业务管理-邻接标签列表", httpMethod = "GET")
    @PreAuthorize("@ss.hasPermi('net:label:list')")
    @GetMapping("/list")
    public TableDataInfo list(BusiNeighbLabel busiNeighbLabel)
    {
        startPage();
        List<BusiNeighbLabelListVo> list = busiNeighbLabelService.selectBusiNeighbLabelList(busiNeighbLabel);
        return getDataTable(list);
    }
    /**
     * 查询网元管理器-sr配置-邻接标签列表
     */
    @ApiOperation(value = "查询网元管理器-sr配置-邻接标签列表", httpMethod = "GET")
    @GetMapping("/ele/list")
    public TableDataInfo eleList(BusiNeighbLabelVo busiNeighbLabelVo)
    {
        startPage();
        List<BusiNeighbLabelListVo> list = busiNeighbLabelService.selectBusiNeighbLabelEleList(busiNeighbLabelVo);
        return getDataTable(list);
    }
    /**
     * 导出业务管理-邻接标签列表
     */
    @ApiOperation(value = "导出业务管理-邻接标签列表", httpMethod = "POST")
    @PreAuthorize("@ss.hasPermi('net:label:export')")
    @Log(title = "业务管理-邻接标签", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusiNeighbLabel busiNeighbLabel)
    {
        List<BusiNeighbLabelListVo> list = busiNeighbLabelService.selectBusiNeighbLabelList(busiNeighbLabel);
        ExcelUtil<BusiNeighbLabelListVo> util = new ExcelUtil<BusiNeighbLabelListVo>(BusiNeighbLabelListVo.class);
        util.exportExcel(response, list, "业务管理-邻接标签数据");
    }

    /**
     * 获取业务管理-邻接标签详细信息
     */
    @ApiOperation(value = "获取业务管理-邻接标签详细信息", httpMethod = "GET")
    @PreAuthorize("@ss.hasPermi('net:label:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(busiNeighbLabelService.selectBusiNeighbLabelById(id));
    }

    /**
     * 新增业务管理-邻接标签
     */
    @ApiOperation(value = "新增业务管理-邻接标签", httpMethod = "POST")
    @PreAuthorize("@ss.hasPermi('net:label:add')")
    @Log(title = "业务管理-邻接标签", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BusiNeighbLabel busiNeighbLabel)
    {
        return toAjax(busiNeighbLabelService.insertBusiNeighbLabel(busiNeighbLabel));
    }

    /**
     * 修改业务管理-邻接标签
     */
    @ApiOperation(value = "修改业务管理-邻接标签", httpMethod = "PUT")
    @PreAuthorize("@ss.hasPermi('net:label:edit')")
    @Log(title = "业务管理-邻接标签", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BusiNeighbLabel busiNeighbLabel)
    {
        return toAjax(busiNeighbLabelService.updateBusiNeighbLabel(busiNeighbLabel));
    }

    /**
     * 删除业务管理-邻接标签
     */
    @ApiOperation(value = "删除业务管理-邻接标签", httpMethod = "DELETE")
    @PreAuthorize("@ss.hasPermi('net:label:remove')")
    @Log(title = "业务管理-邻接标签", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(busiNeighbLabelService.deleteBusiNeighbLabelByIds(ids));
    }

    /**
     * 激活设备
     *
     * @param id
     * @param elementId
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @GetMapping(value = "/activate/{id}/{elementId}")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    public AjaxResult activateDevice(@PathVariable("id") String id,@PathVariable("elementId") String elementId) {
        BusiNeighbLabelListVo busiNeighbLabelListVo = busiNeighbLabelService.selectBusiNeighbLabelVoById(id);

        String noProxml1 ="";
        if (elementId.equals(busiNeighbLabelListVo.getStartElement())){
            noProxml1 = " <mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "        <static-sr>" +
                    "          <static-sr-adjacency nc:operation=\"create\">" +
                    "            <nexthop>"+busiNeighbLabelListVo.getStartOppositeIp()+"</nexthop>" +//对端地址
                    "        <out-ifname>"+busiNeighbLabelListVo.getStartPortName()+"</out-ifname>" +//端口名称
                    "        <sid-value>"+busiNeighbLabelListVo.getStartNeighbLabel()+"</sid-value>" +// 取源宿邻接标签
                    "        </static-sr-adjacency>" +
                    "        </static-sr>" +
                    "        <mpls-te/>" +
                    "      </mpls>";
        }else{
            noProxml1 = " <mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "        <static-sr>" +
                    "          <static-sr-adjacency nc:operation=\"create\">" +
                    "            <nexthop>"+busiNeighbLabelListVo.getEndOppositeIp()+"</nexthop>" +//对端地址
                    "        <out-ifname>"+busiNeighbLabelListVo.getEndPortName()+"</out-ifname>" +//端口名称
                    "        <sid-value>"+busiNeighbLabelListVo.getEndNeighbLabel()+"</sid-value>" +// 取源宿邻接标签
                    "        </static-sr-adjacency>" +
                    "        </static-sr>" +
                    "        <mpls-te/>" +
                    "      </mpls>";
        }
        logger.info("邻接标签激活报文数据noProxml1：" + noProxml1.toString());
        boolean isSend = deviceManager.editConfig(noProxml1, "merge");
        logger.info("isSend结果===================================================：" + isSend);
        if (isSend){
            //同步业务设备网元状态
            BusiElementStatus busiElementStatus = new BusiElementStatus();
            busiElementStatus.setElementId(elementId);
            busiElementStatus.setBusiId(id);
            busiElementStatus.setStatus("1");
            busiElementStatus.setUpdateBy(SecurityUtils.getUsername());
            busiElementStatus.setUpdateTime(DateUtils.getNowDate());
            busiElementStatusService.updateBusiElementStatusByParams(busiElementStatus);

            //更新业务表状态  部分激活2/激活1
            BusiElementStatus busiElementStatus1 = new BusiElementStatus();
            busiElementStatus1.setBusiId(id);
            List<BusiElementStatus> statusList = busiElementStatusService.selectBusiElementStatusList(busiElementStatus1);
            Optional<BusiElementStatus> max = statusList.stream().max(Comparator.comparing(BusiElementStatus::getStatus));
            Optional<BusiElementStatus> min = statusList.stream().min(Comparator.comparing(BusiElementStatus::getStatus));
            BusiNeighbLabel busiNeighbLabel = new BusiNeighbLabel();
            if (max.get().getStatus().equals(min.get().getStatus())){
                if ("0".equals(max.get().getStatus())){
                    busiNeighbLabel.setStatus("0");
                }else {
                    busiNeighbLabel.setStatus("1");
                }
            }else {
                busiNeighbLabel.setStatus("2");
            }
            busiNeighbLabel.setId(id);
            busiNeighbLabel.setStatus("1");
            busiNeighbLabelService.updateBusiNeighbLabel(busiNeighbLabel);
            return AjaxResult.success("激活成功");
        }else{
            return AjaxResult.error("激活失败");
        }

    }
}
